# Copyright (c) 2005,2006,2007 Dynamic Solutions Inc. (support@dynamic-solutions.com)
#
# This file is part of DataZoomer.
#
# DataZoomer is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# DataZoomer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""Login application"""

import dzapp
import dzpage
import dzutil
import dzml
import os
from dzresponse import HTMLResponse

class response:
    def __init__(self,content):
        self.content = content
    def render(self):
        return HTMLResponse(self.content)

class LoginApp(dzapp.App):
    def __init__(self):
        dzapp.App.__init__(self,'login')
        self.iconname = 'blocks'
        self.TOPMENU     = ''
        self.ALERT = ''
        self.TUSERID = ''
        self.css = 1

    def _view_(self):
        # if already authenticated then redirect to home or specified URL
#        content = dzutil.include(os.path.join(zoomer.data_path,'login','loginfm.htm')).replace('<#ALERTS>',self.ALERT)

        content = dzutil.include('loginfm.htm')
        if self.ALERT:
            content = content.replace('<#ALERTS>','<br>'+self.ALERT+'<br>')
        else:
            content = content.replace('<#ALERTS>','')
        content = content.replace('<#TUSERID>',self.TUSERID).replace('<#FORGOT_URL>',dzutil.url_for(app='forgot'))
        zoomer.debug(zoomer.webvars.original_url)
        content = '<center>%s</center>' % content
        return dzpage.Page(content,TITLE='')

    def _api_login(self,**parameters):
        userid = zoomer.webvars.userid
        passwd = zoomer.webvars.passwd

        if len(userid) < zoomer.MIN_USERID_SIZE or len(passwd) < zoomer.MIN_PASSWD_SIZE:
            return response('Invalid login parameters')
        else:
            zoomer.debug('Authenticating %s with %s' % (userid,passwd))
            if self.authenticate(userid,passwd):
                zoomer.debug('User is successfully authenticated')
                session = zoomer.session
                zoomer.sid = session.new_session()
                session.userid  = self.auth.userid
                session.loginid = self.auth.loginid
                session.email   = self.auth.email
                zoomer.debug('session: %s' % session)

                if zoomer.use_cookies:
                    return response('OK')

                return response('SESSION:%s' % zoomer.sid)
            else:
                return response('FAIL')

    def _login(self,**parameters):
        if len(zoomer.webvars.userid) < zoomer.MIN_USERID_SIZE or len(zoomer.webvars.passwd) < zoomer.MIN_PASSWD_SIZE:
#            return dzpage.Page('Invalid login parameters')
            zoomer.debug('Invalid credentials')
            self.ALERT = '<font color=red>Please check your username and password and try again</font>'
            self.TUSERID = zoomer.webvars.userid
            return self._view_()

        else:
            zoomer.debug('Authenticate %s with %s' % (zoomer.webvars.userid,zoomer.webvars.passwd))
            if self.authenticate(zoomer.webvars.userid,zoomer.webvars.passwd):
                zoomer.debug('User is successfully authenticated')
                session = zoomer.session
                zoomer.sid = session.new_session()
                session.userid = self.auth.userid
                session.loginid = self.auth.loginid
                session.email     = self.auth.email
                zoomer.debug('session: %s' % session)

                if not zoomer.webvars.url:
                    url = dzutil.url_for(app=zoomer.home_app)
#                    url = '%s%s' % ( zoomer.site_url,dzutil.url_for(app=zoomer.home_app))
                else:
                    if not 'sid=' in zoomer.webvars.url:
                        url = zoomer.webvars.url + '&sid=' + sid
                    else:
                        url = zoomer.webvars.url

                zoomer.debug('Redirect user to caller application at %s' % url)
                return dzutil.redirect_to(url=url)

            else:
                zoomer.debug('User failed authentication')
                self.ALERT = '<font color=red>Username and password do not match</font>'
                self.TUSERID = zoomer.webvars.userid
                return self._view_()

    def authenticate(self,userid,passwd):
        import dzauthenticate
        self.auth = dzauthenticate.DzAuthenticate(zoomer.db,zoomer.webvars.userid,zoomer.webvars.passwd)
        return self.auth.authenticate()

result = LoginApp()

if __name__ == '__main__':
    import dzmanager
    mgr = dzmanager.Manager()
    app = LoginApp()
    print 'from app:', mgr.run(app)
    print 'resonse: ', zoomer.app_response
    print zoomer.app_response


